<?php
include "../security.inc";
if (isset($_SESSION["debug"]) && $_SESSION["debug"]=='yes') {
	echo "<div style='border: 1px solid green'>";
	var_dump($_POST);
	echo "</div>";
}
if (count($_POST)==0) die(); // initial call, nothing to save

if (count($_POST)==2)
	die("<script type='text/javascript'>alert('Nothing to save !');</script>");

$updates = array();
	
require_once("app_fields.inc");
$applicants_to_update = array();
foreach ($_POST as $key=>$value) {
	if ($key=='from_save') continue;
	if ($key=='timestamp') continue;
	if ($key=='save_button') continue;
	if (substr($key,0,6)=='bool__') continue;
	if ($value === "") $value = null;
	
	$split = explode("$",$key);
	
	if (count($split)<>4)
		die("<script type='text/javascript'>alert('Invalid field: ".$key."');</script>");
	
	$table = $split[0];
	$field = $split[1];
	$key_field = $split[2];
	$key_value = $split[3];
	$i = strpos($key_value, "~");
	if ($i !== false) {
		$w = substr($key_value, $i+1);
		$key_value = substr($key_value, 0, $i);
		$w = explode("~",$w);
		$value = array("*"=>$value);
		for ($i = 0; $i < count($w); $i+=2)
			$value[$w[$i]] = $w[$i+1];
	}
	
	if (!isset($updates[$table]))
		$updates[$table] = array();
	if (!isset($updates[$table][$key_field]))
		$updates[$table][$key_field] = array();
	if (!isset($updates[$table][$key_field][$key_value]))
		$updates[$table][$key_field][$key_value] = array();
	if (!is_array($value))
		$updates[$table][$key_field][$key_value][$field] = $value;
	else {
		if (!isset($updates[$table][$key_field][$key_value][$field])) $updates[$table][$key_field][$key_value][$field] = array();
		array_push($updates[$table][$key_field][$key_value][$field], $value);
	}
	if ($key_field == "applicant_id" && !in_array($key_value,$applicants_to_update)) array_push($applicants_to_update,$key_value);
}

require_once("../DataBase.inc");

if (count($applicants_to_update > 0)) {
	$now = time();
	$conc = array();
	foreach ($applicants_to_update as $id)
		array_push($conc, array("operation"=>"update_applicant","timestamp"=>$now,"username"=>$_SESSION["user"],"object_id"=>$id));
	DataBase::insert_multiples("concurrency",$conc);
	$timestamp = $_POST["timestamp"];
	$query = "";
	foreach ($applicants_to_update as $id) {
		if ($query <> "") $query .= " OR";
		$query .= " object_id=".$id;
	}
	$query = "SELECT * FROM concurrency WHERE operation='update_applicant' AND username<>'".$_SESSION["user"]."' AND timestamp >= ".$timestamp." AND (".$query.")";
	$res = DataBase::query($query);
	if ($res <> false && count($res)>0) {
		DataBase::query("DELETE FROM concurrency WHERE operation='update_applicant' AND username='".$_SESSION["user"]."' AND timestamp=".$now);
		die("<script type='text/javascript'>alert(\"Another user updated some applicants at the same time as you, for security reason you need to refresh the list and update again.\");</script>");
	}
}

// handle cases for exclusion
// 1-Attendance to written exam or interview
if (isset($updates["applicant_more_info"])) {
	if (isset($updates["applicant_more_info"]["applicant_id"])) {
		$applicants = $updates["applicant_more_info"]["applicant_id"];
		foreach ($applicants as $applicant_id=>$applicant_field) {
			if (isset($applicant_field["applicant_more_info_attendee_exam_status"])) {
				$value = $applicant_field["applicant_more_info_attendee_exam_status"];
				if ($value <> null && $value > 1) {
					if (!isset($updates["applicant"]))
						$updates["applicant"] = array();
					if (!isset($updates["applicant"]["applicant_id"]))
						$updates["applicant"]["applicant_id"] = array();
					if (!isset($updates["applicant"]["applicant_id"][$applicant_id]))
						$updates["applicant"]["applicant_id"][$applicant_id] = array();
					//$updates["applicant"]["applicant_id"][$applicant_id]["excluded"] = 1;
                                        /*
                                         * code changed by vannak 2012/03/23
                                         */
					$updates["applicant"]["applicant_id"][$applicant_id]["excluded_reason"] = "Written Exam Attendance";
				}
			}
			if (isset($applicant_field["applicant_interview_attendance"])) {
				$value = $applicant_field["applicant_interview_attendance"];
				if ($value <> null && $value > 1) {
					if (!isset($updates["applicant"]))
						$updates["applicant"] = array();
					if (!isset($updates["applicant"]["applicant_id"]))
						$updates["applicant"]["applicant_id"] = array();
					if (!isset($updates["applicant"]["applicant_id"][$applicant_id]))
						$updates["applicant"]["applicant_id"][$applicant_id] = array();
					$updates["applicant"]["applicant_id"][$applicant_id]["excluded"] = 1;
					$updates["applicant"]["applicant_id"][$applicant_id]["excluded_reason"] = "Interview Attendance";
				}
			}
		} 
	}
}

$errors = "";

foreach ($updates as $table_name=>$table_updates) {
	foreach ($table_updates as $key_field=>$key_values) {
		foreach ($key_values as $key_value=>$fields_to_update) {
			if (isset($_SESSION["debug"]) && $_SESSION["debug"]=='yes') {
				echo "<div style='border: 1px solid red'>";
				echo "UPDATE: ".$table_name.".".$key_field."=".$key_value.": ";
				foreach ($fields_to_update as $f=>$v) echo $f."=".$v."//";
				echo "</div>";
			}
			$normal_values = array();
			$where_values = array();
			foreach ($fields_to_update as $fk=>$fv)
				if (is_array($fv)) $where_values[$fk] = $fv; else $normal_values[$fk] = $fv;
			if (count($normal_values)>0) {
				DataBase::update($table_name, array($key_field=>$key_value), $normal_values);
				$errno = DataBase::last_error_number();
				if ($errno <> 0) {
					$errors .= "Update Error #".$errno.": ".DataBase::last_error_message()."\\r\\n";
				} else {
					if (DataBase::number_of_affected_rows() == 0) {
						$result = DataBase::select($table_name, array($key_field), array($key_field=>$key_value));
						if ($result === false || count($result)==0) {
							$normal_values[$key_field] = $key_value;
							DataBase::insert($table_name, $normal_values);
							if ($errno <> 0)
								$errors .= "Insert Error #".$errno.": ".DataBase::last_error_message()."\\r\\n";
						}
					}
				}
			}
			if (count($where_values)>0) {
				foreach ($where_values as $field=>$list_wvalues) {
					foreach ($list_wvalues as $wvalues) {
						$where = array($key_field=>$key_value);
						foreach ($wvalues as $wk=>$wv)
							if ($wk=="*") $value = $wv; else $where[$wk] = $wv;
						DataBase::update($table_name, $where, array($field=>$value));
						$errno = DataBase::last_error_number();
						if ($errno <> 0) {
							$errors .= "Update Error #".$errno.": ".DataBase::last_error_message()."\\r\\n";
						} else {
							if (DataBase::number_of_affected_rows() == 0) {
								$result = DataBase::select($table_name, null, $where);
								if ($result === false || count($result)==0) {
									$values = array();
									$values[$key_field] = $key_value;
									$values[$field] = $value;
									foreach ($where as $wk=>$wv) $values[$wk] = $wv;
									DataBase::insert($table_name, $values);
									if ($errno <> 0)
										$errors .= "Insert Error #".$errno.": ".DataBase::last_error_message()."\\r\\n";
								}
							}
						}
					}
				}
			}
			if (isset($_SESSION["debug"]) && $_SESSION["debug"]=='yes') {
				global $sql_debug;
				echo $sql_debug;
				$sql_debug = "";
			}
		}
	}
}
if (strlen($errors) == 0)
	echo("<script type='text/javascript'>alert('Fields correctly saved.');parent.fields_saved();</script>");
else
	echo("<script type='text/javascript'>alert('Some errors occured while saving fields:\\r\\n".$errors."');</script>");
?>